<template>
  <div class="register-container">
    <svg-icon icon-class="registerBg" width="100%" height="40vh" class="icon"/>
    <div class="register-content">
      <!-- 头部导航 -->
      <van-nav-bar title="Create Account" class="page-nav-bar">
        <template #left>
          <span @click="$router.back()">
            <svg-icon icon-class="fanhui" width="30px" height="30px" class="icon"/>
          </span>
        </template>
      </van-nav-bar>

      <!-- 登录注册 -->
      <van-form @submit="onSubmit" ref="loginForm">
        <!-- 用户名 -->
        <van-field
          v-model="user.username"
          name="username"
          label="用户名"
          placeholder="1-10个字符"
        >
          <template #left-icon>
            <svg-icon icon-class="xin-qinglv" width="20px" height="20px" class="icon"/>
          </template>
        </van-field>

        <!-- 手机号 -->
        <van-field
          v-model="user.mobile"
          name="mobile"
          label="手机号"
          placeholder="手机号"
          :rules="userRules.mobile"
        >
          <template #left-icon>
            <svg-icon icon-class="xin-xinxi" width="20px" height="20px" class="icon"/>
          </template>
        </van-field>

        <!-- 密码 -->
        <van-field
          v-model="user.password"
          name="password"
          label="密码"
          placeholder="6-12位数字、大小写字母"
        >
          <template #left-icon>
            <svg-icon icon-class="xin-yuechi" width="20px" height="20px" class="icon"/>
          </template>
        </van-field>

        <!-- 验证码 -->
        <van-field
          v-model="user.code"
          name="code"
          label="验证码"
          placeholder="大小写敏感"
          :rules="userRules.code"
        >
          <template #left-icon>
            <svg-icon icon-class="qianyue-xin" width="20px" height="20px" class="icon"/>
          </template>

          <template #button>
            <van-count-down :time="8 * 1000" format="ss 秒" v-if="isCountDownShow" @finish="countFn"/>
            <van-button
              class="smsBtn"
              round
              size="small"
              type="primary"
              @click="sendSms"
              native-type="button"
              v-else
            >send Code
            </van-button>
          </template>
        </van-field>
        <van-popup v-model="show" position="top" :overlay="false" class="codePopup">
          获取验证码成功！<br/>您的验证码是：{{ codeContent }}
        </van-popup>
        <!-- 提交 -->
        <div style="margin: 28px;" class="button-wrap">
          <van-button block type="info" native-type="submit">submit</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>

/* 验证码246810 */

import { userRegisterAPI, userSendSmsAPI } from '@/api'
import SvgIcon from '@/components/svgIcon/index.vue'

export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        mobile: '',
        code: '',
        username: '',
        password: ''
      },
      show: false,
      codeContent: '',
      userRules: {
        mobile: [
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3|5|7|8]\d{9}$/, message: '手机格式错误' }
          // 第一位是1 第二位是 3578中的一个, 9位数
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^[A-Za-z0-9]{4}$/, message: '验证码格式错误' }
        ]
      },
      isCountDownShow: false // 是否展示倒计时
    }
  },
  components: {
    SvgIcon
  },
  methods: {
    countFn () {
      this.isCountDownShow = false
      this.show = false
    },
    async onSubmit () {
      try {
        // 通过加载提示来阻止用户高频的请求点击
        this.$toast.loading({
          duration: 0, // 持续显示加载提示，直到触发成功或失败才会关闭
          message: '登录中...', // 提示内容
          forbidClick: true // 是否禁用背景点击
        })
        console.log(this.user.code)
        if (this.user.code !== this.codeContent) return this.$toast.fail('验证码错误')

        const res = await userRegisterAPI({
          username: this.user.username,
          password: this.user.password,
          mobile: this.user.mobile
        })
        if (res.data.status === 1) return this.$toast.fail(res.data.message)
        this.$store.commit('setUser', res.data.data)
        // 返回上一页
        this.$router.back()
        this.$toast.success('注册成功！')
      } catch (error) {
        console.log(error)
        // 通过不同的响应代码来判断提示错误的内容
        if (error.response && error.response.status === 400) {
          this.$toast.fail('手机号或验证码错误')
        } else {
          this.$toast.fail('网络异常，请稍后重试')
        }
      }
    },

    // 发送验证码
    async sendSms () {
      try {
        // 通过form表单的验证规则，来判断是否符合手机格式
        await this.$refs.loginForm.validate('mobile')
        // 如果一个接口返回成功的返回值不需要在代码中使用，则可以省略赋值操作
        const res = await userSendSmsAPI()
        console.log(res)
        // 当接口调用成功时，展示倒计时组件
        this.isCountDownShow = true
        this.$toast.success('发送验证码成功')
        this.show = !this.show
        this.codeContent = res.data.data
        // alert(res.data.data)
      } catch (error) {
        console.log(error)
        if (error.response && error.response.status === 404) {
          this.$toast.fail('手机号不正确')
        } else if (error.response && error.response.status === 429) {
          this.$toast.fail('访问繁忙请一分钟后重试')
        } else if (error.name === 'mobile') {
          this.$toast.fail('手机号不正确')
        } else {
          this.$toast.fail('网络异常，请稍后重试')
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.register-container {
  height: 100vh;
  background-color: #fff2e6;

  .register-content {
    height: 60vh;
    background-color: #fff;
    border-radius: 30px 30px 0 0;

    .smsBtn {
      color: #fff;
      background-color: #d1746d;
      border: none;
      font-size: 12px;
      letter-spacing: 1px;
    }

    .page-nav-bar {
      height: 80px;
      background-color: transparent;
    }

    .van-cell {
      height: 55px;
      align-items: center;
    }

    ::v-deep .page-nav-bar .van-nav-bar__title {
      max-width: none;
      color: #666666;
      font-size: 31px;
      font-weight: bolder;
      height: 40px;
      margin-top: 40px;
      letter-spacing: 1px;
    }

    ::v-deep .page-nav-bar .van-nav-bar__left {
      top: 24px;
    }

    .codePopup {
      left: 50%;
      transform: translateX(-50%);
      width: 80%;
      border-radius: 20px;
      line-height: 25px;
      font-size: 16px;
      height: 10vh;
      opacity: 0.8;
      padding: 15px;
    }

    .button-wrap button {
      height: 50px;
      border-radius: 20px;
      border: none;
      background-color: #eaa49d;
      Letter-spacing: 3px;
      font-size: 18px;
    }
  }

}
</style>
